import React, { Suspense } from "react";
import { BrowserRouter, Routes, Route, Navigate, Outlet } from "react-router-dom";
import Login from "./pages/Login";
import MainLayout from "./pages/MainLayout";
import Page1 from "./pages/Page1";
import Page2 from "./pages/Page2";
// import Page3 from "./pages/Page3";
// import Page4 from "./pages/Page4";
// import Page5 from "./pages/Page5";
// import Page6 from "./pages/Page6";
import { useMenu } from "./context/MenuContext";
import NotFound from "./pages/NotFound";


//动态导入，符合 Vite/rollup 的优化建议
const Page3 = React.lazy(() => import('./pages/Page3'));
const Page4 = React.lazy(() => import('./pages/Page4'));
const Page5 = React.lazy(() => import('./pages/Page5'));
const Page6 = React.lazy(() => import('./pages/Page6'));
const Page7 = React.lazy(() => import('./pages/Page7'));


// 动态路由组件映射
// 这里的组件名需要和后端返回的菜单组件名一致
// 新增页面只需在 componentMap 注册即可
const componentMap = {
  Page1,
  Page2,
  Page3,
  Page4,
  Page5,
  Page6,
  Page7,
};

// 需要登录才能访问的路由
// 登录页，登录成功后会设置 token到 localStorage
function RequireAuth({ children }) {
  const isLoggedIn = localStorage.getItem("isLoggedIn");
  return isLoggedIn ? children : <Navigate to="/login" replace />;
}


// 递归渲染路由
function EmptyOutlet() {
  return <Outlet />;
}

// 父级 element 必须是包含 <Outlet /> 的组件，否则嵌套路由不会渲染
function renderRoutes(menus, componentMap, parentPath = "") {
  return menus.map(menu => {
    const fullPath = parentPath ? `${parentPath}/${menu.path}` : menu.path;
    if (menu.children && menu.children.length > 0) {
      return (
        <Route key={fullPath} path={menu.path} element={<EmptyOutlet />}>
          {renderRoutes(menu.children, componentMap, fullPath)}
        </Route>
      );
    }
    return (
      <Route
        key={fullPath}
        path={menu.path}
        element={componentMap[menu.component] ? React.createElement(componentMap[menu.component]) : null}
      />
    );
  });
}


export default function App() {
  const { menus } = useMenu();

  return (
    <BrowserRouter>
      <Suspense fallback={<div>页面加载中...</div>}>
        <Routes>
          <Route path="/login" element={<Login />} />
          <Route
            path="/"
            element={
              <RequireAuth>
                <MainLayout />
              </RequireAuth>
            }
          >
            <Route path="page1" element={<Page1 />} />
            <Route path="page2" element={<Page2 />} />

            {/* 动态路由 */}
            {renderRoutes(menus, componentMap)}

            {/* 默认展示路由-首页配置 */}
            <Route index element={<Page1 />} />
            {/* 子路由404 */}
            <Route path="*" element={<NotFound />} />
          </Route>
          {/* 主路由404 */}
          <Route path="*" element={<NotFound />} />
        </Routes>
      </Suspense>
    </BrowserRouter>
  );
}



